package com.cn.por.util.tree;

import java.util.ArrayList;
import java.util.List;
/**
 * 将具备父子关系的对象集合装换为树形结构对象或json字符串，
 * 数据库应该返回具有排序规则的对象集合，并且没有父级菜单的为顶级。
 * @author 26983
 */
public class TreeBuilder {
	
	private List<TreeNode> nodes;
	
	public TreeBuilder(List<TreeNode> treeNodes) {
		this.nodes=treeNodes;
	}
	public TreeBuilder() {
		
	}
	/**
	 * 构建树形结构的对象集合，实现思路：第一步获取到没有父级菜单的节点也就是顶级节点，
	 * 第二步循环找顶级及其子节点的子节点。
	 * @return
	 */
	public List<TreeNode> buildTree() {
		List<TreeNode> newTree = new ArrayList<TreeNode>();
		for(TreeNode trees : nodes) {
			if(null == trees.getParentCode() || "".equals(trees.getParentCode())) {
				newTree.add(trees);
				addChilderNode(trees,nodes);
			}
		}
		return newTree;
	}
	
	private void addChilderNode(TreeNode tree,List<TreeNode> listNode) {
		for(TreeNode node: listNode) {
			if(tree.getCode().equals(node.getParentCode())) {
				List<TreeNode> newNode = new ArrayList<TreeNode>();
				newNode.add(node);
				tree.setChilders(newNode);
				addChilderNode(node,listNode);
			}
		}
	}
	
	
	public static void main(String[] args) {
		List<TreeNode> treesn = new ArrayList<TreeNode>();
		TreeNode t1= new TreeNode();
		t1.setId("1");
		t1.setName("顶级");
		treesn.add(t1);
		TreeNode t3= new TreeNode();
		t3.setId("3");
		t3.setName("底级");
		t3.setParentCode("2");
		treesn.add(t3);
		TreeNode t2= new TreeNode();
		t2.setId("2");
		t2.setName("中级");
		t2.setParentCode("1");
		treesn.add(t2);
		TreeBuilder treb = new TreeBuilder(treesn);
		List<TreeNode> sortList = treb.buildTree();
		System.err.println(sortList.toString());
	}

}
